import { ChatMessage, RenderItem, ChatMessageType } from "../interfaces"
import config from '../config'
import _ from 'lodash'
import { TemplateRender } from "./common"

const plugins = config.plugins?.map(p => {
  return {
    ...p,
    regexp: new RegExp(p.regexp)
  }
}) || []

const exec_to_matches_item = (str: string) => {
  for (let i = 0; i < plugins.length; i++) {
    const { type, regexp, matches, render } = plugins[i];
    const arr = regexp.exec(str)
    if (arr) {
      const match_result = matches.reduce((o, k, i) => {
        o[k] = arr[i]
        return o
      }, {} as any)
      const { body = arr[0] } = match_result
      const item: RenderItem & { index: number } = {
        index: arr.index,
        type, body
      }
      if (type === ChatMessageType.LINK_WITH_TITLE) {
        item.render = {
          ...render,
          url: TemplateRender(render.url, match_result),
        }
      }
      return item
    }
  }
  return null
}

const plugins_render = (str: string) => {
  const render_items: RenderItem[] = []
  let matches_item = exec_to_matches_item(str)
  while (matches_item) {
    const { index, ...item } = matches_item
    if (index > 0) {
      render_items.push({
        type: ChatMessageType.TXT,
        body: str.substring(0, index),
      })
    }
    render_items.push(item)
    str = str.substring(index + item.body.length)
    matches_item = exec_to_matches_item(str)
  }
  if (str) {
    render_items.push({
      type: ChatMessageType.TXT,
      body: str,
    })
  }
  return render_items
}

export const message_render = (msg: ChatMessage): ChatMessage => {
  // 已经处理过、不再处理
  if (msg.render_items) {
    return msg
  }
  let render_items: RenderItem[]
  const { type, body } = msg
  try {
    switch (type) {
      case ChatMessageType.TXT:
        render_items = plugins_render(msg.body)
        break;
      default:
        render_items = [{type: type, body}]
    }
  } catch (e) {
    console.log(e)
  }
  return {
    ...msg,
    render_items,
  }
}
